package com.xuyh.pdf.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xuyh
 * @email 497418972@qq.com
 * @data 2019年3月21日12:39:27
 * @description 合并PDF
 */
public class MergePDF {
    /**
     * 合并输出文件名称
     */
    private final static String MERGE_OUTPUT_FILE = "D:\\pdf\\hebing\\shijuan\\t.pdf";
    /**
     * 合并PDF的文件
     */
    private final static String MERGE_PDF_PATH = "D:\\pdf\\hebing\\shijuan\\1";


    public static void main(String[] args) {
        FileUtils.createOutputFile(MERGE_OUTPUT_FILE);
        mergePdf(pdfFilePath());
    }


    public static List<String> pdfFilePath() {
        List<String> list = new ArrayList<>();
        File file = new File(MERGE_PDF_PATH);
        File[] files = file.listFiles();
        assert files != null;
        for (File f : files) {
            list.add(f.getAbsolutePath());
        }
        return list;
    }

    public static void mergePdf(List<String> list) {
        Document document = null;
        PdfCopy copy = null;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(MERGE_OUTPUT_FILE);
            document = new Document();
            copy = new PdfCopy(document, fos);
            document.open();

            for (String path : list) {
                PdfReader reader = new PdfReader(path);
                int n = reader.getNumberOfPages();
                for (int i = 1; i <= n; i++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, i);
                    copy.addPage(page);
                }

                if (reader != null) {
                    reader.close();
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (document != null) {
                    document.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (copy != null) {
                    copy.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
